-- 对象池
local ObjectPool = class("ObjectPool")
local GameUtils = require("utils.GameUtils")

function ObjectPool:ctor(template, poolManager, key)
    self._poolManager = poolManager
    self._template = template
    self._objectList = {}
    self.isDestroy = false
    self._key = key
end

function ObjectPool:getObject(...)
    if #self._objectList == 0 then
        local object = self._template.new(...)
        object:setObjectPool(self)
        return object
    end
    local len = #self._objectList
    local object = self._objectList[len]
    object.gameObject:SetActive(true)
    object:reset()
    table.remove(self._objectList, len)
    return object
end

function ObjectPool:recyleObject(object)
    if self.isDestroy then
        return
    end
    object.gameObject:SetActive(false)
    table.insert(self._objectList, object)
end

function ObjectPool:destroy(noRemove)
    self.isDestroy = true
    for i = 1, #self._objectList do
        GameUtils.destroy(self._objectList[i].gameObject)
    end
    self._objectList = {}
    if not noRemove then
        self._poolManager:removeObjectPool(self._key)
    end
end

return ObjectPool
